using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.XPath;
using System.IO;
using System.Text;
using System.Security.Permissions;
using MagnoliaTableAdapters;


public partial class ReportDailyRunDetail : System.Web.UI.Page
{
    static DataTable dtResults = new DataTable();
    static string pageResultStr = "";
    static string reportResultStr = "";

    protected override void Render(HtmlTextWriter writer)
    {
        // Write the HTML into this string builder
        StringBuilder sb = new StringBuilder();
        HtmlTextWriter hWriter = new HtmlTextWriter(new StringWriter(sb));
        base.Render(hWriter);

        // Store to a string
        pageResultStr = sb.ToString();

        // Write it back to the server's HTTP Stream -// *** skip this if you don't want to display the rendered content
        writer.Write(pageResultStr);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Page.Title = ConfigurationManager.AppSettings["PageTitle"] + " - Reporting - Daily Run (Detail)";
        
        // Add calendar to date fields
        TextBox_DateFrom.Attributes.Add("onfocus", "this.select();lcs(this);");
        TextBox_DateFrom.Attributes.Add("onclick", "event.cancelBubble=true;this.select();lcs(this);");
        TextBox_DateTo.Attributes.Add("onfocus", "this.select();lcs(this);");
        TextBox_DateTo.Attributes.Add("onclick", "event.cancelBubble=true;this.select();lcs(this);");

        Btn_RunReport.Attributes.Add("onfocus", "cs_blur();");
        Btn_Reset.Attributes.Add("onfocus", "cs_blur();");
        Btn_Print.Attributes.Add("onclick", "window.print();");
        Btn_ExportCSV.Attributes.Add("onclick", "showExportPopup();");

        Lbl_Messages.Text = "Please search for an asset and provide any other report parameters before clicking \"Run Report\" to view the results";

        Lbl_ReportTitle.Style["float"] = "none";
        Lbl_ReportTitle.Style["padding-bottom"] = "5px";
        Lbl_ReportTitle.Style["display"] = "block";

        ExportFileName.Value = Convert.ToString(Page.Title) + ".doc";
    }

    protected void Btn_RunReport_Click(object sender, EventArgs e)
    {
        Lbl_Alerts.Visible = false;
        Lbl_ReportTitle.Visible = false;
        Lbl_Messages.Visible = false;
        GridView_Results.Visible = false;
        

        if ((ListBox_Results.SelectedIndex < 0)
                || (TextBox_DateFrom.Text.Trim().Length == 0)
                || (TextBox_DateTo.Text.Trim().Length == 0))
        {
            Lbl_Alerts.Text = "Please fill out all report parameters";
            Lbl_Alerts.Style.Add("color", "Red");
            Lbl_Messages.Text = "Please provide your report parameters and click \"Run Report\" to view the results";
            Lbl_Messages.Visible = true;
            Lbl_Alerts.Visible = true;
            return;
        }

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SuperSignConnectionString"].ConnectionString);
        try
        {
            // Open connection to db
            conn.Open();

            string sProc = "sproc_WEB_ReportDailyRunDetail";
            SqlCommand cmd = new SqlCommand(sProc, conn);
            cmd.CommandType = CommandType.StoredProcedure;

            // set paramter
            DbParameter param = cmd.CreateParameter();
            param.ParameterName = "@AssetIdList";
            String assetIdStr = "";
            foreach (ListItem item in ListBox_Results.Items)
            {
                if (item.Selected)
                    assetIdStr += item.Value + ",";
            }
            //assetIdStr = assetIdStr.Substring(0, assetIdStr.Length - 2);
            param.Value = (assetIdStr);
            param.DbType = DbType.String;
            cmd.Parameters.Add(param);

            // set paramter
            param = cmd.CreateParameter();
            param.ParameterName = "@DateStart";
            param.Value = Convert.ToDateTime(TextBox_DateFrom.Text);
            param.DbType = DbType.DateTime;
            cmd.Parameters.Add(param);

            // set paramter
            param = cmd.CreateParameter();
            param.ParameterName = "@DateEnd";
            param.Value = Convert.ToDateTime(TextBox_DateTo.Text);
            param.DbType = DbType.DateTime;
            cmd.Parameters.Add(param);

            // execute the stored procedure and return the results
            //DataTable dtResults = new DataTable();
            dtResults.Columns.Clear();
            dtResults.Rows.Clear();

            SqlDataAdapter sqlAdapter = new SqlDataAdapter(cmd);
            sqlAdapter.Fill(dtResults);

            if (dtResults.Rows.Count == 0)
            {
                Lbl_Messages.Text = "The given report parameters returned no results";
                Lbl_Messages.Visible = true;
                GridView_Results.Visible = false;
                Btn_Print.Enabled = false;
                Btn_ExportCSV.Enabled = false;
            }
            else // if (dtResults.Rows.Count <= 1000)
            {
                Lbl_ReportTitle.Text = "ABC SuperSign Daily Detail Report<br />";
                Lbl_ReportTitle.Text += TextBox_DateFrom.Text + " - " + TextBox_DateTo.Text + "<br /><br />";

                GridViewHelper helper = new GridViewHelper(GridView_Results);
                helper.RegisterGroup("Date", true, true);
                helper.GroupHeader += new GroupEvent(helper_GroupHeader);
                helper.RegisterSummary("Channel", SummaryOperation.Count, "Date");
                helper.RegisterSummary("Channel", AddCount, TotalCount);
                helper.RegisterSummary("Length", AddSubtotalLength, SubtotalLengths, "Date");
                helper.RegisterSummary("Length", AddTotalLength, TotalLengths);
                helper.RegisterSummary("Asset", AddOverallTotals, OverallTotals);
                helper.GroupSummary += new GroupEvent(helper_GroupSummary);

                GridView_Results.DataSource = dtResults;
                GridView_Results.DataBind();

                GridView_Results.Visible = true;
                Lbl_ReportTitle.Visible = true;
                Lbl_Messages.Visible = false;
                Btn_Print.Enabled = true;
                Btn_ExportCSV.Enabled = true;
            }
        }
        catch (Exception ex)
        {
            String Message = ex.Message;
            throw ex;
        }
        finally
        {
            conn.Close();
        }
    }

    static int lengthSubtotalSeconds = 0;
    static int lengthTotalSeconds = 0;
    static int rowCounter = 0;

    private void AddSubtotalLength(string column, string group, object value)
    {
        DateTime tmpRowDate = Convert.ToDateTime("00:" + value);

        lengthSubtotalSeconds += tmpRowDate.Minute * 60 + tmpRowDate.Second;
    }

    private void AddTotalLength(string column, string group, object value)
    {
        DateTime tmpRowDate = Convert.ToDateTime("00:" + value);

        lengthTotalSeconds += tmpRowDate.Minute * 60 + tmpRowDate.Second;

     }

    private object SubtotalLengths(string column, string group)
    {

        int hours = lengthSubtotalSeconds / 3600;
        int minutes = (lengthSubtotalSeconds % 3600) / 60;
        int seconds = (lengthSubtotalSeconds % 3600) % 60;

        lengthSubtotalSeconds = 0;

        return Convert.ToString(hours).PadLeft(2, '0') + 
            ":" + Convert.ToString(minutes).PadLeft(2, '0') +
            ":" + Convert.ToString(seconds).PadLeft(2, '0');
    }

    private object TotalLengths(string column, string group)
    {
        int hours = lengthTotalSeconds / 3600;
        int minutes = (lengthTotalSeconds % 3600) / 60;
        int seconds = (lengthTotalSeconds % 3600) % 60;

        lengthTotalSeconds = 0;

        return Convert.ToString(hours).PadLeft(2, '0') +
            ":" + Convert.ToString(minutes).PadLeft(2, '0') +
            ":" + Convert.ToString(seconds).PadLeft(2, '0');
    }

    private void AddCount(string column, string group, object value)
    {
        rowCounter++;
    }

    private object TotalCount(string column, string group)
    {
        int tmpTotal = rowCounter;
        rowCounter = 0;
        return tmpTotal;
    }

    private void AddOverallTotals(string column, string group, object value)
    {
        // do nothing

    }

    private object OverallTotals(string column, string group)
    {
        string tmpStr = "<span style='font-weight:bold; float:right'>Overall Totals:</span>";
        return tmpStr;
    }

    protected void helper_GroupHeader(string groupName, object[] values, GridViewRow row)
    {
        row.Style["font-size"] = "13px";
        row.Style["font-weight"] = "bold";
        if (groupName == "Date")
        {
            row.BackColor = System.Drawing.Color.FromArgb(236, 236, 236);
            row.Cells[0].Text = row.Cells[0].Text;
        }
    }



    private void helper_GroupSummary(string groupName, object[] values, GridViewRow row)
    {
        row.Cells[0].HorizontalAlign = HorizontalAlign.Right;
        row.Cells[0].Style["font-weight"] = "bold";
        row.Cells[0].Text = "Totals:";
        row.BackColor = System.Drawing.Color.LightGray;
    }


    protected void Btn_Reset_Click(object sender, EventArgs e)
    {
        TextBox_DateFrom.Text = "";
        TextBox_DateTo.Text = "";
        ListBox_Results.Items.Clear();
        Lbl_Alerts.Visible = false;
    }
    protected void Btn_Search_Click(object sender, EventArgs e)
    {
        // clear previous results
        ListBox_Results.Items.Clear();

        // query to get a list of items
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SuperSignConnectionString"].ConnectionString);
        try
        {
            conn.Open();

            String sProc = "sproc_WEB_GetListAsset";

            SqlCommand cmd = new SqlCommand(sProc, conn);
            cmd.CommandType = CommandType.StoredProcedure;

            // set paramter
            DbParameter param = cmd.CreateParameter();
            param.ParameterName = "@XML";
            param.Value = Session["ListSearchString"];
            param.DbType = DbType.Xml;
            cmd.Parameters.Add(param);

            param = cmd.CreateParameter();
            param.ParameterName = "@IncludeDisabled";
            param.Value = Convert.ToBoolean(Session["ListSearchIncludeDisabled"]);
            param.DbType = DbType.Boolean;
            cmd.Parameters.Add(param);

            // execute the stored procedure and return the results
            XmlReader xReader = cmd.ExecuteXmlReader();
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(xReader);
            xReader.Close();

            XmlNodeList nodes = xDoc.SelectNodes("//ASSET");
            foreach (XmlNode xNode in nodes)
            {
                ListItem item = new ListItem();
                item.Text = Convert.ToString(xNode.Attributes["Name"].InnerXml);
                item.Value = Convert.ToString(xNode.Attributes["ID"].InnerXml);
                try
                {
                    item.Attributes.Add("label", Convert.ToString(xNode.Attributes["CreatedOn"].InnerXml));
                }
                catch (Exception exception)
                {
                    String err = exception.Message;
                }

                ListBox_Results.Items.Add(item);
            }
        }
        catch (Exception ex)
        {
            String err = ex.Message;
            Lbl_Messages.Text = "The report returned an error.  Please check your parameters and try again";
            Lbl_Messages.Visible = true;
        }
        finally
        {
            conn.Close();
        }
    }
    protected void WriteReportToFile()
    {
        // Create the file to which data will be exported
        String FileName = Convert.ToString(Page.Title) + ".doc";
        String ExportPath = Server.MapPath("Exports");
        String FilePath = ExportPath + "\\" + FileName;
        if (File.Exists(FilePath))
        {
            File.Delete(FilePath);
        }
        StreamWriter sw = new StreamWriter(FilePath, false);
        
        // Get Report From Page string
        String startIndexStr = "<div class=\"reportResults\">";
        String endIndexStr = "</table>";

        int startIndex = pageResultStr.IndexOf(startIndexStr);
        int endIndex = pageResultStr.IndexOf(endIndexStr);
        reportResultStr = pageResultStr.Substring(startIndex, endIndex - startIndex + 8);
        reportResultStr += "</div></div>";

        sw.Write(reportResultStr);
        sw.Close();
    }

    protected void Btn_ExportCSV_Click(object sender, EventArgs e)
    {
        WriteReportToFile();
        //ExportGridToCSV();

        Lbl_ReportTitle.Text = "ABC SuperSign Daily Detail Report<br />";
        Lbl_ReportTitle.Text += TextBox_DateFrom.Text + " - " + TextBox_DateTo.Text + "<br /><br />";

        GridViewHelper helper = new GridViewHelper(GridView_Results);
        helper.RegisterGroup("Date", true, true);
        helper.GroupHeader += new GroupEvent(helper_GroupHeader);
        helper.RegisterSummary("Channel", SummaryOperation.Count, "Date");
        helper.RegisterSummary("Channel", AddCount, TotalCount);
        helper.RegisterSummary("Length", AddSubtotalLength, SubtotalLengths, "Date");
        helper.RegisterSummary("Length", AddTotalLength, TotalLengths);
        helper.RegisterSummary("Asset", AddOverallTotals, OverallTotals);
        helper.GroupSummary += new GroupEvent(helper_GroupSummary);

        GridView_Results.DataSource = dtResults;
        GridView_Results.DataBind();

        GridView_Results.Visible = true;
        Lbl_ReportTitle.Visible = true;
        Lbl_Messages.Visible = false;
        Btn_Print.Enabled = true;
        Btn_ExportCSV.Enabled = true;
    }
}
